package src

import (
	"fmt"
	"sync"
)

var (
	wg      sync.WaitGroup
	counter int
	rw      sync.RWMutex
)

func OrderedOutput() {
	var channels [10]chan int
	for i := 0; i < 10; i++ {
		channels[i] = make(chan int)
	}

	output := func(ch <-chan int, next chan<- int) {
		defer wg.Done()

		num := <-ch
		fmt.Println(num)

		if next != nil {
			next <- num + 1
			close(next)
		}
	}

	wg.Add(10)
	for i := 0; i < 9; i++ {
		go output(channels[i], channels[i+1])
	}
	go output(channels[9], nil)

	channels[0] <- 1
	close(channels[0])

	wg.Wait()
}

func OOTwo() {
	output := func(id int) {
		defer wg.Done()
		for {
			rw.Lock()
			if id == counter {
				counter++
				fmt.Println(counter)
				rw.Unlock()
				break
			}
			rw.Unlock()
		}
	}

	wg.Add(10)
	for i := 0; i < 10; i++ {
		go output(i)
	}
	wg.Wait()
}
